package web.language.helper

class EntryController {
    def scaffold = true

    def save() {

        String uid = java.util.UUID.randomUUID().toString();

        def entry = new Entry(params);
        entry.setId(uid)
        entry.save()
        def dicId = session.getAt("dicId")
        def dic = Dictionary.findById(dicId)
        dic.addToEntries(entry)
        dic.save(flash: true)

        redirect action: "list", id: dicId
    }

    def list() {
        def dicId = null
        if (params["id"] == null) {
            dicId = session.getValue("dicId")
        } else {
            dicId = params["id"]
        }
        session.putValue("dicId", dicId)

        Dictionary dic = Dictionary.findById(dicId)
        session.putValue("dicName", dic.name)

        [ entries : getEntryItems(dic), dicName: params["dicName"]]
    }

    List<EntryItem> getEntryItems(Dictionary dic) {
        List<EntryItem> items = new ArrayList<EntryItem>()
        dic.entries.each { entry ->
            def stat = entry.statistic.find {
                stat -> stat.user.id == session.user.id
            }
            if (stat == null) {
                items.add(new EntryItem(entry, 0, 0))
            } else {
                items.add(new EntryItem(entry, stat.wrong, stat.right))
            }
        }
        items
    }

    def dicList() {
        redirect controller: "dictionary", action: "list"
    }

    def delete() {
        def dicId = session.getValue("dicId")
        Dictionary dic = Dictionary.findById(dicId)

        Entry entry = Entry.findById(params["id"])
        dic.removeFromEntries(entry)

        entry.delete()
        redirect action: "list"
    }

    def deleteAll() {
        def dicId = session.getValue("dicId")
        Dictionary dic = Dictionary.findById(dicId)
        for (Entry entry in dic.entries) {
            entry = Entry.findById(entry.id)
            dic.removeFromEntries(entry)
            entry.delete()
        }
        dic.delete(flash: true)

        dicList()
    }

    def importent() {
        redirect controller: 'importent', action: 'form'
    }

    class EntryItem {

        Entry entry
        public Integer wrong
        public Integer right

        EntryItem(Entry entry, Integer wrong, Integer right) {
            this.entry = entry
            this.wrong = wrong
            this.right = right
        }

        public String getId() {
            this.entry.id
        }

        public String getPhrase() {
            this.entry.phrase
        }

        public String getTranslate() {
            this.entry.translate
        }
    }
}
